<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class CreatePlayerController extends MY_Controller {

	function __construct() {
		parent::__construct();
	}

	/**
	 * @Authorize()
	 */
	public function index() {
		if($this->is_post()) {
			//$error = new ErrorVo();
			
			//validação dos campos.
			$rules = array(
				array(
					'field' => 'player_name',
					'label' => '',
					'rules' => 'xss_clean'
				)
			);
				
			$validate = $this->form_validation->validate_data( $rules );
			//Verificaa validação do formulario
				
			if( $validate[ 'status' ] ) {
				$form = $validate['data'];
				
				$player = new Player();
				
				$players_batch = array();//Recebe todos os jogadores criados
				foreach($this->userdata['players']['players'] as $k => $p) {
					$player_info = array(
						'player_name' => (empty($form['player_name'][$k]))?$p['player_name']:$form['player_name'][$k],
						'player_birthday' => $p['player_birthday'],
						'player_token' => create_guid("pl"),
						'player_age' => $p['player_age'],
						'player_weight' => $p['player_weight'],
						'player_height' => $p['player_height'],
						'country_id' => $p['country_id'],
						'player_position_id' => $p['player_position_id'],
						'player_deft' => $p['player_deft']
					);
					
					$status = $player->cratePlayerStatus($p['player_age']);
					
					//Insere o jogador;
					$this->model->insert_player(array_merge($player_info, $status));
					
					$player_id = $this->shared_model->get_lest_id();
					
					$ralation_team_player = array(
						'team_id' => $this->userdata['team_id'],
						'player_id' => $player_id
					);
					
					$this->model->insert_relation_to_team($ralation_team_player);
				}
				
				
				//Retido da sessão onde carregava todos os dados do jogador
				$this->session->unset_userdata('players');
				
				$user_create_players = cur_date();
				
				//Setando novo valor em data de criação do time
				$this->session->unset_userdata('user_create_players');
				$this->session->set_userdata('user_create_players', $user_create_players);
				
				//Atualiza dados da tabela usuário
				$this->db->where('user_id', $this->userdata['user_id']);
				$this->shared_model->update_table('users', array('user_create_players' => $user_create_players));
				
				//Redireciona para area de logado
				redirect(url(URL_DEFAULT_LOGGED));
			}
			else {
				echo FORM_MESSAGE_ERROR_VALIDADE;
			}
		}
		else {
			$this->set_data('title', PAGE_TITLE);
			$this->set_data('description', PAGE_DESCRIPTION);
			$players = $this->_create_user();
			$this->set_data('players', $players);
			
			$this->session->unset_userdata('players');
			$this->session->set_userdata('players', $players);
			
			$this->load_view('createPlayer/index');
		}
	}
	
	
	//===FUNÇÔES PRIVATES
	/**
	 * Cria as informçãoes basicas de cada jogador. como nome, posição, idade, e define se sera destro ou canhoto
	 * */
	private function _create_user(){
		$userdata = get_userdata($this->session);
		
		$retorno = array(
			'players' => array()
		);
		
		//Retonar nomes aleatorios pelo pais.
		$get_names_db = $this->model->get_names($userdata['country_id']);
		
		$position_arr = array();
		$get_position_db = $this->model->get_positions();
		
		foreach ($get_position_db as $p)
			$position_arr[$p['player_position_id']] = $p['player_position_name'];
		
		$create_player = new Player();		
		$typeFormation = rand(1,4);
		
		$retorno['type_formation'] = $typeFormation;
		
		foreach ($get_names_db as $k=>$name) {
			$player = $create_player->createPlayer($name['name'], $name['country_id'], $k, $typeFormation, $position_arr);
			array_push($retorno['players'], $player);
		}
		
		return $retorno;
		
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */